<template>
  <div class="app-container">
    <el-page-header @back="goBack" style="margin-bottom: 10px">
    </el-page-header>
   <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="区间开始时间" prop="startTime">
        <el-time-picker clearable
                        value-format="yyyy-MM-dd HH:mm:ss"
                        v-model="queryParams.startTime"
                        placeholder="请选择区间开始时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="区间结束时间" prop="endTime">
        <el-time-picker clearable
                        value-format="yyyy-MM-dd HH:mm:ss"
                        v-model="queryParams.endTime"
                        placeholder="请选择区间结束时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>-->
    <el-row :gutter="10" class="mb8" style="margin-bottom: 10px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:price:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:price:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:price:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:price:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="priceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="区间开始时间" align="center" prop="startTime" width="180">
       <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{h}:{i}:{s}') }}</span>
        </template>-->
      </el-table-column>
      <el-table-column label="区间结束时间" align="center" prop="endTime" width="180">
        <!--<template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{h}:{i}:{s}') }}</span>
        </template>-->
      </el-table-column>
      <el-table-column label="电价" align="center" prop="electricCharge"/>
      <el-table-column label="原价" align="center" prop="originalPrice"/>
      <el-table-column label="服务费" align="center" prop="serviceFee"/>
      <el-table-column label="停车费" align="center" prop="stopFee"/>
      <el-table-column label="创建人" align="center" prop="createName"/>
      <el-table-column label="修改人" align="center" prop="updateName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="authority">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:price:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:price:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场站电区间价设置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="区间开始时间" prop="startTime">
          <el-time-picker clearable style="width: 340px"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="form.startTime"
                          placeholder="请选择区间开始时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="区间结束时间" prop="endTime">
          <el-time-picker clearable style="width: 340px"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="form.endTime"
                          placeholder="请选择区间结束时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="电价" prop="electricCharge">
          <el-input  v-model="form.electricCharge" placeholder="请输入电价" style="width: 340px"/>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input  v-model="form.originalPrice" placeholder="请输入原价" style="width: 340px"/>
        </el-form-item>
        <el-form-item label="服务费" prop="serviceFee">
          <el-input  v-model="form.serviceFee" placeholder="请输入服务费" style="width: 340px"/>
        </el-form-item>
        <el-form-item label="停车费" prop="stopFee">
          <el-input  v-model="form.stopFee" placeholder="请输入停车费" style="width: 340px"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listPrice, getPrice, delPrice, addPrice, updatePrice, getOperatorList, getStationList,getPriceLast,getValidationRepeat} from "@/api/smart/operator/electricityPrice";
  export default {
    name: "Price",
    data() {
      var checkStartVal = (rule, value, callback) => {
        var startTime = new Date(this.form.startTime);
        var endTime = new Date(this.form.endTime);
        if (startTime >= endTime) {
          return callback(new Error('开始时间需小于结束时间'))
        } else {
          this.$refs.form.clearValidate('startTime')
          this.$refs.form.clearValidate('endTime')
          return callback()
        }
      }
      var checkEndVal = (rule, value, callback) => {
        var startTime = new Date(this.form.startTime);
        var endTime = new Date(this.form.endTime);
        if (startTime >= endTime) {
          return callback(new Error('开始时间需小于结束时间'))
        } else {
          this.$refs.form.clearValidate('startTime')
          this.$refs.form.clearValidate('endTime')
          return callback()
        }
      }
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 场站电区间价设置表格数据
        priceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        authority:null,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          strategyId: null,
          operatorId: null,
          stationId: null,
          startTime: null,
          endTime: null,
          electricCharge: null,
          originalPrice: null,
          serviceFee: null,
          stopFee: null,
          createName: null,
          updateName: null,
          priceTypeCode:null,
        },
        //服务商列表
        operatorList: [],
        //服务商列表
        stationList: [],
        stationListTwo: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          /*operatorId: [
            {required: true, message: "请选择运营商", trigger: "change"}
          ],
          stationId: [
            {required: true, message: "请选择站点", trigger: "change"}
          ],*/
          startTime: [
            {required: true, message: "请选择区间开始时间", trigger: "change"},
            {validator: checkStartVal}
          ],
          endTime: [
            {required: true, message: "请选择区间结束时间", trigger: "change"},
            {validator: checkEndVal}
          ],
          serviceFee: [
            {required: true, message: "请输入服务费", trigger: "blur"},
            {pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "请输入正确的服务费格式"}
          ],
          stopFee: [
            {required: true, message: "请输入停车费", trigger: "blur"},
            {pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "请输入正确的停车费格式"}
          ],
          electricCharge: [
            {required: true, message: "请输入电费", trigger: "blur"},
            {pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "请输入正确的电费格式"}
          ],
          originalPrice: [
            {required: true, message: "请输入原价", trigger: "blur"},
            {pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "请输入正确的电费格式"}
          ],
        },
        count:null,
        date:this.$moment().format('YYYY-MM-DD '),
      };
    },
    created() {
      /*查询运营商列表*/
      this.getOperatorList();
      this.authority = this.$auth.hasPermi("system:price:edit")
      this.queryParams.priceTypeCode = this.$route.query.priceTypeCode;
      /*查询电价区间列表*/
      this.getList();
    },
    methods: {
      /*查询运营商列表*/
      getOperatorList() {
        getOperatorList().then(response => {
          this.operatorList = response.data;
        })
      },
      /*查询运营商列表*/
      getStationList() {
        let param = {"id": this.form.operatorId}
        getStationList(param).then(response => {
          this.stationList = response.data;
        })
      },
      /** 查询最新一条数据*/
      getPriceLast(){
        let param = {"priceTypeCode": this.queryParams.priceTypeCode}
        getPriceLast(param).then(response => {
          if(typeof response.data=="undefined"){
            this.form.startTime=this.date+'00:00:00';
          }else{
            var housh=parseInt(response.data.endTime.slice(0,2));
            if(housh==23){
            }else{
              var number=housh+1;
              var b=number.toString();
              //var c=response.data.endTime.slice(0,11)
              if(b.length==1){
                this.form.startTime=this.date+'0'+b+':00:00';
              }else{
                this.form.startTime=this.date+b+':00:00';
              }
            }
          }
        })
      },
      getStationListTwo() {
        let param = {"id": this.queryParams.operatorId}
        getStationList(param).then(response => {
          this.stationListTwo = response.data;
        })
      },
      /** 查询场站电区间价设置列表 */
      getList() {
        this.loading = true;
        listPrice(this.queryParams).then(response => {
          this.priceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          strategyId: null,
          operatorId: null,
          stationId: null,
          startTime: null,
          endTime: null,
          electricCharge: null,
          originalPrice: null,
          serviceFee: null,
          stopFee: null,
          createName: null,
          createTime: null,
          updateName: null,
          updateTime: null,
          priceTypeCode:this.queryParams.priceTypeCode,
          priceTypeId:this.$route.query.priceTypeId,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getPriceLast()
        this.open = true;
        this.title = "添加场站电区间价设置";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getPrice(id).then(response => {
          //查询站点信息
          this.form = response.data;
          this.form.startTime=this.date+response.data.startTime;
          this.form.endTime=this.date+response.data.endTime;
          this.open = true;
          this.title = "修改场站电区间价设置";
        });
      },
      goBack(){
        this.$router.go(-1)
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if('00'==this.form.startTime.slice(14,16)&&'00'==this.form.startTime.slice(17,19)&&('00'==this.form.endTime.slice(14,16)||'59'==this.form.endTime.slice(14,16))&&('00'==this.form.endTime.slice(17,19)||'59'==this.form.endTime.slice(17,19))){
            getValidationRepeat(this.form).then(response => {
              if(parseInt(response.data)>0){
                this.$message({message: '该时间段已设置，请勿重复设置。', type: 'warning'});
              }else{
                if (valid) {
                  if (this.form.id != null) {
                    updatePrice(this.form).then(response => {
                      this.$modal.msgSuccess("修改成功");
                      this.open = false;
                      this.getList();
                    });
                  } else {
                    addPrice(this.form).then(response => {
                      this.$modal.msgSuccess("新增成功");
                      this.open = false;
                      this.getList();
                    });
                  }
                }
              }
            });
          }else{
            this.$message({message: '时间间隔有误,只能是整点。', type: 'warning'});
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除场站电区间价设置编号为"' + ids + '"的数据项？').then(function () {
          return delPrice(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('operator/electricityPrice/export', {
          ...this.queryParams
        }, `price_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
